package com.nuoniu.sibanyun.service.production.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.erp.ErpNumberSet;
import com.nuoniu.sibanyun.entity.production.*;
import com.nuoniu.sibanyun.mapper.erp.ErpNumberSetMapper;
import com.nuoniu.sibanyun.mapper.production.MaMrpMapper;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.erp.IErpNumberSetService;
import com.nuoniu.sibanyun.service.production.IMaMrpDatailService;
import com.nuoniu.sibanyun.service.production.IMaMrpService;
import com.nuoniu.sibanyun.service.production.IVProductionWorkDetailService;
import com.nuoniu.sibanyun.service.utils.ErpUtils;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 物料需求计划主表 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2023-05-22
 */
@Service
public class MaMrpServiceImpl extends ServiceImpl<MaMrpMapper, MaMrp> implements IMaMrpService {

    @Autowired
    private IErpAccountService accountService;
    @Autowired
    private ErpNumberSetMapper numberSetMapper;
    @Autowired
    private IErpNumberSetService numberSetService;
    @Autowired
    private IMaMrpDatailService maMrpDatailService;
    @Autowired
    private IVProductionWorkDetailService productionWorkDetailService;

    @Override
    public void saveOrder(MaMrp maMrpOperation) {
        if(maMrpOperation == null) {
            throw new NuoNiuException("数据不能为空");
        }
        if(maMrpOperation.getOrderDetailList() == null || maMrpOperation.getOrderDetailList().size() == 0) {
            throw new NuoNiuException("单据明细不能为空");
        }

        UserInfo userInfo = UserThreadLocal.get();
        if(maMrpOperation.getId() == null) {
            maMrpOperation.setCompanyId(userInfo.getCompanyId());
            maMrpOperation.setAccountId(accountService.getCurrentAccountId());
            maMrpOperation.setCreateUserId(userInfo.getUserId());
            maMrpOperation.setVoucherCode(getCode());
            maMrpOperation.setCreateUserName(userInfo.getRealName());
            maMrpOperation.setVoucherState(-1);
        }


        Boolean result = this.saveOrUpdate(maMrpOperation);
        if(result) { //保存明细
            List<MaMrpDetail> orderDetailList = maMrpOperation.getOrderDetailList();
            List<Long> detailIds = new ArrayList<>();
            orderDetailList.forEach(p -> {
                p.setAccountId(accountService.getCurrentAccountId());
                p.setCompanyId(userInfo.getCompanyId());
                p.setOrderId(maMrpOperation.getId().intValue());
                //添加 不删除的明细ID
                if (p.getId() != null) {
                    detailIds.add(p.getId());
                }
            });

            if (maMrpOperation.getId() != null){
                //删除明细
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.eq("order_id", maMrpOperation.getId());
                if(detailIds != null && detailIds.size() > 0) {
                    wrapper.notIn("id", detailIds);
                }
                maMrpDatailService.remove(wrapper);
            }
            //保存单据明细表
            maMrpDatailService.saveOrUpdateBatch(orderDetailList);
        }
    }

    @Override
    public void delete(Long id) {
        this.removeById(id);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("order_id", id);
        maMrpDatailService.remove(wrapper);
    }

    @Override
    public void submit(Long id, Integer status) {
        if(null == id || null == status || (null != status && (status > 0 || status < -1 )))throw new NuoNiuException("参数错误");
        UserInfo userInfo = UserThreadLocal.get();
        MaMrp main = this.getById(id);
        if(main == null) {
            throw new NuoNiuException("记录不存在");
        }

        /**  统一校验 提交状态 */
        ErpUtils.checkSubmitStatus(main.getVoucherState(), status);

        //提交
        main.setVoucherState(status);
        main.setSubmitDate(LocalDateTime.now());
        main.setSubmitUserId(userInfo.getUserId());
        main.setSubmitUserName(userInfo.getRealName());
        this.updateById(main);
    }

    @Override
    public void examine(Long id, Integer status) {
        if(status == 0) {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("source_voucher_id", id);
            wrapper.eq("source_voucher_type", "RequirementPlan");
            int count = productionWorkDetailService.count();
            if(count > 0) {
                throw new NuoNiuException("已生单，不能弃审");
            }

            wrapper = new QueryWrapper();
            wrapper.eq("source_voucher_id", id);
            wrapper.eq("source_voucher_type","PurchaseRequisition");
        }
        UserInfo userInfo = UserThreadLocal.get();
        MaMrp maMrp = new MaMrp();
        maMrp.setVoucherState(status);
        maMrp.setId(id);
        maMrp.setReviewerUserName(userInfo.getRealName());
        maMrp.setReviewerUserId(userInfo.getUserId());
        updateById(maMrp);
    }

    @Override
    public String getCode() {
        UserInfo userInfo = UserThreadLocal.get();
        Integer currentAccountId = accountService.getCurrentAccountId();
        ErpNumberSet numberSet = numberSetMapper.getByCode("RequirementPlan", userInfo.getCompanyId(), currentAccountId);
        String dateStr = numberSet.getMedian() == 1 ? "%Y-%m-%d" : "%Y-%m";
        String code = baseMapper.getNewestCode(userInfo.getCompanyId(), dateStr);
        return numberSetService.getCode(numberSet, code);
    }

    @Override
    public void closed(Long id, Integer status) {
        UserInfo userInfo = UserThreadLocal.get();
        MaMrp maMrp = new MaMrp();
        maMrp.setClosedState(status);
        maMrp.setClosedDate(LocalDateTime.now());
        maMrp.setCloserId(userInfo.getUserId());
        maMrp.setCloserName(userInfo.getUserName());
        maMrp.setId(id);
        updateById(maMrp);
    }

    @Override
    public void merge(List<MaMrpDetail> maMrpDatailList) {
        Map<Integer, MaMrpDetail> count = new HashMap<>();
        List<Integer> updateId = new ArrayList<>();
        List<Long> deleteId = new ArrayList<>();
        maMrpDatailList.forEach(p -> {
            if(count.get(p.getInventoryId()) == null) {
                updateId.add(p.getInventoryId());
                count.put(p.getInventoryId(), p);
            } else {
                MaMrpDetail datail = count.get(p.getInventoryId());
                deleteId.add(p.getId());
                datail.setBaseQuantity(p.getBaseQuantity().add(datail.getBaseQuantity()));
                count.put(p.getInventoryId(), datail);
            }
        });

        //修改合并数据
        for(Integer id : updateId) {
            maMrpDatailService.updateById(count.get(id));
        }

        //删除多余数据
        if(deleteId.size() > 0) {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.in("id", deleteId);
            maMrpDatailService.remove(wrapper);
        }
    }

    @Override
    public void split(List<MaMrpDetail> maMrpDatailList) {
        maMrpDatailList.forEach(p -> {
            p.setCompanyId(UserThreadLocal.get().getCompanyId());
            p.setAccountId(accountService.getCurrentAccountId());
        });
        maMrpDatailService.saveOrUpdateBatch(maMrpDatailList);
    }
}
